//
//  BHHomeChildViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/8.
//

import UIKit

class BHHomeChildViewController: BHBaseViewController {
    
    // 通知首页可以滚动了
    var callHomeCanScroll:(() -> Void)?
    // 记录当前子视图列表是否在滚动
    var childScrolling: Bool = false
    
    // 通知首页刷新停止
    var stopRefreshBlock:(() -> Void)?
    
    
    lazy var waterFlowLayout: DPHomeWaterFlowLayout = {
        let layout = DPHomeWaterFlowLayout.init()
        layout.delegate = self
        return layout
    }()
    lazy var collectionView: UICollectionView = {
        let view = UICollectionView.buildCollectionView(layout: self.waterFlowLayout)
        view.backgroundColor = .color_f8f8f8
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    lazy var serviceManager: BHCircleServiceManager = {
        let manager = BHCircleServiceManager.init()
        return manager
    }()
    
    /**子列表类型
     0 圈子
     1 精彩赛事
     2 运动场馆
     3 更多趣玩
     */
    open var childType: Int = 0
    open var childCanScorll: Bool = false
    fileprivate var stadiumArray: [BHCommonStadiumModel] = []
    fileprivate var gameArray: [BHCommonGameModel] = []
    fileprivate var columnListArray: [BHCircleListModel] = [] // 圈子
    fileprivate var funArray: [BHFunListInfoModel] = [] // 趣玩

    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .color_f8f8f8
        self.view.addSubview(self.collectionView)
        self.registerCell()
        self.collectionView.mas_makeConstraints { (make) in
            make?.left.right()?.top()?.height()?.equalTo()(self.view)
        }
        
        if self.childType == 0 {
            self.responseNetService()
        }
        
        self.collectionView.addloadMore { [weak self] in
            self?.page += 1
            if self?.childType == 0 {
                self?.serviceManager.loadCircleListService(columId: nil, page: self?.page ?? 1)
            }
            if self?.childType == 1 {
                self?.loadGameService()
            }
            if self?.childType == 2 {
                self?.loadStadiumService()
            }
            if self?.childType == 3 {
                self?.loadFunService()
            }
        }
        
        if self.childType == 0 {
            NotificationCenter.default.addObserver(self, selector: #selector(forceRefresh), name: NSNotification.Name.init(String.deleteSelfCircleKey), object: nil)
            
            NotificationCenter.default.addObserver(self, selector: #selector(forceRefresh), name: NSNotification.Name.init(String.addNewCircleRefreshKey), object: nil)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.collectionView.frame =   CGRect(x: 0, y: 0, width: UIScreen.width, height: self.view.bh_height)
    }
    
    private func registerCell() {
        self.collectionView.register(UINib.init(nibName: "BHHomeCircleItemCell", bundle: nil), forCellWithReuseIdentifier: "BHHomeCircleItemCell")
        self.collectionView.register(UINib.init(nibName: "BHWonderfulGameCell", bundle: nil), forCellWithReuseIdentifier: "BHWonderfulGameCell")
        self.collectionView.register(UINib.init(nibName: "BHSportAndPlaceCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHSportAndPlaceCollectionViewCell")
        self.collectionView.register(UINib.init(nibName: "BHMoreFunCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHMoreFunCollectionViewCell")
    }
    
    
    @objc func forceRefresh() {
        self.page = 1
        self.serviceManager.loadCircleListService(columId: nil, page: self.page)
    }
    
    func begainRefresh() {
        if self.childType == 0 {
            if self.columnListArray.count == 0 {
                self.serviceManager.loadCircleListService(columId: nil, page: 1)
            }
        }
        if self.childType == 1 {
            if self.gameArray.count == 0 {
                self.loadGameService()
            }
        }
        if self.childType == 2 {
            if self.stadiumArray.count == 0 {
                self.loadStadiumService()
            }
        }
        
        if self.childType == 3 {
            if self.funArray.count == 0 {
                self.loadFunService()
            }
        }
    }
    
}

extension BHHomeChildViewController {
    func begainRefreshToPageOne()  {
        self.page = 1
        if self.childType == 0 {
            self.serviceManager.loadCircleListService(columId: nil, page: 1)
        }
        if self.childType == 1 {
            self.loadGameService()
        }
        if self.childType == 2 {
            self.loadStadiumService()
        }
        
        if self.childType == 3 {
            self.loadFunService()
        }
    }
}

extension BHHomeChildViewController {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.childCanScorll == false{
            scrollView.contentOffset.y = 0
        }else {
            if scrollView.contentOffset.y <= 0 {
                self.childCanScorll = false
                self.callHomeCanScroll?()
            }
        }
    }
}

extension BHHomeChildViewController: DPHomeWaterFlowLayoutDelegate {
    
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        if self.childType == 0 {
            let model = self.columnListArray[indexPath.row]
            return  BHHomeCircleItemCell.circleHeight+model.textHeight+58
        }else if self.childType == 1 {
            return BHWonderfulGameCell.gameHeight
        }else if self.childType == 2 {
            let model = self.stadiumArray[indexPath.row]
            return model.cellHeight
        }else if self.childType == 3 {
            return BHMoreFunCollectionViewCell.moreFunHeight
        }else {
            return 0
        }
    }
    
    func columnNumber(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> Int {
        if self.childType == 0 {
            return 2
        }else {
            return 1
        }
    }
    
    func interitemSpacing(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> CGFloat {
        if self.childType == 0 {
            return 8
        }else {
            return 0
        }
    }
    func lineSpacing(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> CGFloat {
        if self.childType == 0 {
            return 10
        }else {
            return 0
        }
    }
    func insetForSection(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> UIEdgeInsets {
        if self.childType == 0 {
            return UIEdgeInsets(top: 10, left: 16, bottom: 0, right: 16)
        }else {
            return .zero
        }
    }
}


extension BHHomeChildViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.childType == 0 {
            return self.columnListArray.count
        }
        if self.childType == 1 {
            return self.gameArray.count
        }
        if self.childType == 2 {
            return self.stadiumArray.count
        }
        if self.childType == 3 {
            return self.funArray.count
        }
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if self.childType == 0 {
            if self.columnListArray.count == 0 {
                return .zero
            }
            let model = self.columnListArray[indexPath.row]
            let halfW = (UIScreen.width-40)/2.0
            return  CGSize(width: halfW-1, height: BHHomeCircleItemCell.circleHeight+model.textHeight+58)
            
        }else if self.childType == 1 {
            return CGSize(width: UIScreen.width, height: BHWonderfulGameCell.gameHeight)
        }else if self.childType == 2 {
            let model = self.stadiumArray[indexPath.row]
            return CGSize(width: UIScreen.width, height: model.cellHeight)
        }else if self.childType == 3 {
            return CGSize(width: UIScreen.width, height: BHMoreFunCollectionViewCell.moreFunHeight)
        }else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.childType == 0 {
            let model = self.columnListArray[indexPath.row]
            BHRouter.shared.bh_goCircleDetail(circleId: model.circleId)
        }
        if self.childType == 1 {
            let model = self.gameArray[indexPath.row]
            BHRouter.shared.bh_goGameDetail(gameId: model.gameId)
        }
        if self.childType == 2 {
            let model = self.stadiumArray[indexPath.row]
            BHRouter.shared.bh_goStadiumDetail(stadium: model.stadiumId)
        }
        if self.childType == 3 {
            let model = self.funArray[indexPath.row]
            BHRouter.shared.bh_goFunDetail(funId: model.funId)
        }
    }
}

extension BHHomeChildViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if self.childType == 0 {
            return  self.cellForCircle(indexPath)
        }else if self.childType == 1 {
            return self.cellForGame(indexPath)
        }else if self.childType == 2 {
            return self.cellForSport(indexPath)
        }else if self.childType == 3 {
            return self.cellForMoreFun(indexPath)
        }else {
            return UICollectionViewCell()
        }
    }
    
}

// MARK: - 圈子
extension BHHomeChildViewController {
    func cellForCircle(_ indexPath: IndexPath) -> BHHomeCircleItemCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHHomeCircleItemCell", for: indexPath) as! BHHomeCircleItemCell
        let model = self.columnListArray[indexPath.row]
        cell.circleModel = model
        cell.likeBtn.addBtnAction(action: {[weak self] (_) in
            self?.serviceManager.circleLikeOrNot(model: model)
        }, for: .touchUpInside)
        return cell
    }
}


// MARK: - 精彩赛事
extension BHHomeChildViewController {
    func cellForGame(_ indexPath: IndexPath) -> BHWonderfulGameCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHWonderfulGameCell", for: indexPath) as! BHWonderfulGameCell
        let model = self.gameArray[indexPath.row]
        cell.model = model
        return cell
    }
}


// MARK: - 运动场馆
extension BHHomeChildViewController {
    func cellForSport(_ indexPath: IndexPath) -> BHSportAndPlaceCollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHSportAndPlaceCollectionViewCell", for: indexPath) as! BHSportAndPlaceCollectionViewCell
        let model = self.stadiumArray[indexPath.row]
        cell.model = model
        return cell
    }
}

// MARK: - 更多趣玩
extension BHHomeChildViewController {
    func cellForMoreFun(_ indexPath: IndexPath) -> BHMoreFunCollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHMoreFunCollectionViewCell", for: indexPath) as! BHMoreFunCollectionViewCell
        let model = self.funArray[indexPath.row]
        cell.model = model
        return cell
    }
}

// 场馆
extension BHHomeChildViewController {
    func loadStadiumService()  {
        let stadium = BHHTTPClient.init()
        stadium.get(url: String.home_stadium_listUrl, paramters: ["pageNo":"\(self.page)","pageSize":"20","longitude":BHLocationManager.shared.longitude,"latitude":BHLocationManager.shared.latitude]) { (success, errorMsg, responseObject)  in
            self.stopRefreshBlock?()
            self.collectionView.endLoading()
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseObject, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.stadiumArray.count != 0 {
                        self.stadiumArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHCommonStadiumModel.init()
                    model.parseDic(dic as! [String : Any])
                    self.stadiumArray.append(model)
                }
                self.collectionView.reloadData()
                if self.stadiumArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
                
            }else {
                BHToast.toast(text: errorMsg)
                if self.page != 1 {
                    self.page -= 1
                }
            }
        }
    }
}

//MARK: 赛事列表
extension BHHomeChildViewController {
    func loadGameService()  {
        let stadium = BHHTTPClient.init()
        stadium.get(url: String.home_game_listUrl, paramters: ["pageNo":"\(self.page)","pageSize":"20","longitude":BHLocationManager.shared.longitude,"latitude":BHLocationManager.shared.latitude]) { (success, errorMsg, responseObject)  in
            self.stopRefreshBlock?()
            self.collectionView.endLoading()
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseObject, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.gameArray.count != 0 {
                        self.gameArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHCommonGameModel.init()
                    model.parseDic(dic as! [String : Any])
                    self.gameArray.append(model)
                }
                self.collectionView.reloadData()
                if self.gameArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
                
            }else {
                BHToast.toast(text: errorMsg)
                if self.page != 1 {
                    self.page -= 1
                }
            }
        }
    }
}

// MARK: 圈子
extension BHHomeChildViewController {
    
    func responseNetService()  {
        self.serviceManager.circleColumnListResponseBlock = { [weak self] (success,errorMsg,total,array) in
            self?.stopRefreshBlock?()
            self?.collectionView.endLoading()
            if success == true {
                if self?.page == 1 {
                    self?.collectionView.endLoadWithNoMoreData(false)
                    self?.columnListArray.removeAll()
                }
                self?.columnListArray.append(contentsOf: array)
                self?.collectionView.reloadData()
                
                if self?.columnListArray.count ?? 0 >= total {
                    self?.collectionView.endLoadWithNoMoreData(true)
                }
            }else {
                if self?.page ?? 1 > 1 {
                    self?.page -= 1
                }
            }
            
        }
        
        self.serviceManager.circleLikeOrNotResponseBlock = {[weak self] (success, errorMsg) in
            self?.collectionView.reloadData()
        }
    }
}


// MARK: 趣玩
extension BHHomeChildViewController {
    func loadFunService()  {
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.fun_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.stopRefreshBlock?()
            self.collectionView.endLoading()
            
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.funArray.count != 0 {
                        self.funArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHFunListInfoModel.init()
                    model.parseDic(dic as! [String : Any])
                    self.funArray.append(model)
                }
                self.collectionView.reloadData()
                if self.funArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
                    
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        dic["typeOneValue"] = ""
        dic["typeTwoValue"] = ""
        dic["cityId"] = ""
        dic["regionId"] = ""
        dic["search"] = ""
        dic["sortType"] = ""
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        
        return dic
    }
}
